import TIM from "tim-js-sdk";
import TIMUploadPlugin from "tim-upload-plugin";
import Cookies from "js-cookie";
import Vue from "vue";
import {followAdd, getAppId} from "@/api/im";
import {emojiMap, emojiUrl} from './emojiMap';

export function formateTime(secondTime) {
    const time = secondTime;
    let newTime;
    let hour;
    let minite;
    let seconds;
    if (time >= 3600) {
        hour = parseInt(time / 3600) < 10 ? `0${parseInt(time / 3600)}` : parseInt(time / 3600);
        minite = parseInt(time % 60 / 60) < 10 ? `0${parseInt(time % 60 / 60)}` : parseInt(time % 60 / 60);
        seconds = time % 3600 < 10 ? `0${time % 3600}` : time % 3600;
        if (seconds > 60) {
            minite = parseInt(seconds / 60) < 10 ? `0${parseInt(seconds / 60)}` : parseInt(seconds / 60);
            seconds = seconds % 60 < 10 ? `0${seconds % 60}` : seconds % 60;
        }
        newTime = `${hour}:${minite}:${seconds}`;
    } else if (time >= 60 && time < 3600) {
        minite = parseInt(time / 60) < 10 ? `0${parseInt(time / 60)}` : parseInt(time / 60);
        seconds = time % 60 < 10 ? `0${time % 60}` : time % 60;
        newTime = `00:${minite}:${seconds}`;
    } else if (time < 60) {
        seconds = time < 10 ? `0${time}` : time;
        newTime = `00:00:${seconds}`;
    }
    return newTime;
}
export function getToAccount(conversationID,conversationType) {
    switch (conversationType) {
        case 'C2C':
            return conversationID.replace('C2C', '');

        case 'GROUP':
            return conversationID.replace('GROUP', '');

        default:
            return conversationID;
    }
}
export function getPhoneByImUserID(userID) {
    return userID.replace('dhs_personal_', '').replace('dhs_enterprise_', '');
}
/**
 * @description 该方法返回一个promise对象，请注意使用then，catch捕获并进行逻辑处理
 * @description catch回调只有一个参数，即为错误信息提示，可以使用element-ui提示错误消息
 * @description then回调中请自行跳转至im页面
 * @description 请注意判断发送对象，因hr和求职者im账号独立，采用前缀拼接手机号方式作为账号，方法中自动获取当前身份相反的前缀拼接手机号进行发送，例如当前为hr，就会像角色为求职者的手机号发送，反之亦然
 * @param message
 * @param toPhone
 * @returns {Promise<unknown>}
 */

export function sendHiMessage(message,toPhone,positionId=null){
    return new Promise((resolve, reject)=>{
        if(typeof message!='string'){
            reject('message 参数错误 需要的是string 传入的是'+typeof message)
        }
        if(!['number','string'].includes(typeof toPhone)){
            reject('toPhone 参数错误 需要的是number/string 传入的是'+typeof toPhone)
        }
        if(message.length===0){
            reject('message内容不能为空')
        }
        toPhone=toPhone.toString();
        if(toPhone.length!==11){
            reject('toPhone 参数长度错误')
        }
        const userIdentity = Cookies.get('identity');
        const to=userIdentity==1?'dhs_enterprise_'+toPhone:'dhs_personal_'+toPhone;
        const messageContext=Vue.prototype.tim.createTextMessage({
            to,
            conversationType:Vue.prototype.TIM.TYPES.CONV_C2C,
            payload:{
                text:message
            }
        })
        const positionMessage = Vue.prototype.tim.createCustomMessage({
            to,
            conversationType: Vue.prototype.TIM.TYPES.CONV_C2C,
            payload: {
                data: 'position',
                description: '',
                extension: JSON.stringify({id:positionId}),
            }
        })
        const loading=Vue.prototype.$loading({
            fullscreen:true,
            text:'发送中',
        })
        Vue.prototype.tim.sendMessage(positionMessage).then((pres)=>{
            setTimeout(()=>{
                Vue.prototype.tim.sendMessage(messageContext).then((res)=>{
                    followAdd({follow:3,mobile:toPhone,followType:userIdentity}).then((sRes)=>{
                        resolve();
                    }).catch((sRes)=>{
                        reject('消息发送成功 服务器同步失败');
                    }).finally(()=>{
                        loading.close()
                    })
                }).catch(()=>{
                    loading.close();
                    reject('消息发送失败')
                });
            },500)
        }).catch(()=>{
            loading.close();
            reject('消息发送失败')
        })
    })
}

export function parseImage(message) {
    return [{
        name: 'image',
        // 这里默认渲染的是 1080P 的图片
        src: message.payload.imageInfoArray[0].url
    }];
}
export function parseText(message) {
    const renderDom = [];
    let temp = message.payload.text;
    let left = -1;
    let right = -1;

    while (temp !== '') {
        left = temp.indexOf('[');
        right = temp.indexOf(']');

        switch (left) {
            case 0:
                if (right === -1) {
                    renderDom.push({
                        name: 'span',
                        text: temp
                    });
                    temp = '';
                } else {
                    const _emoji = temp.slice(0, right + 1);

                    if (emojiMap[_emoji]) {
                        renderDom.push({
                            name: 'img',
                            src: emojiUrl + emojiMap[_emoji]
                        });
                        temp = temp.substring(right + 1);
                    } else {
                        renderDom.push({
                            name: 'span',
                            text: '['
                        });
                        temp = temp.slice(1);
                    }
                }

                break;

            case -1:
                renderDom.push({
                    name: 'span',
                    text: temp
                });
                temp = '';
                break;

            default:
                renderDom.push({
                    name: 'span',
                    text: temp.slice(0, left)
                });
                temp = temp.substring(left);
                break;
        }
    }

    return renderDom;
}
export function caculateTimeago(dateTimeStamp) {
    const minute = 1000 * 60; // 把分，时，天，周，半个月，一个月用毫秒表示

    const hour = minute * 60;
    const day = hour * 24;
    const week = day * 7;
    const now = new Date().getTime(); // 获取当前时间毫秒

    const diffValue = now - dateTimeStamp; // 时间差

    let result = '';

    if (diffValue < 0) {
        return;
    }

    const minC = diffValue / minute; // 计算时间差的分，时，天，周，月

    const hourC = diffValue / hour;
    const dayC = diffValue / day;
    const weekC = diffValue / week;

    if (weekC >= 1 && weekC <= 4) {
        result = ` ${parseInt(weekC, 10)}周前`;
    } else if (dayC >= 1 && dayC <= 6) {
        result = ` ${parseInt(dayC, 10)}天前`;
    } else if (hourC >= 1 && hourC <= 23) {
        result = ` ${parseInt(hourC, 10)}小时前`;
    } else if (minC >= 1 && minC <= 59) {
        result = ` ${parseInt(minC, 10)}分钟前`;
    } else if (diffValue >= 0 && diffValue <= minute) {
        result = '刚刚';
    } else {
        const datetime = new Date();
        datetime.setTime(dateTimeStamp);
        const Nyear = datetime.getFullYear();
        const Nmonth = datetime.getMonth() + 1 < 10 ? `0${datetime.getMonth() + 1}` : datetime.getMonth() + 1;
        const Ndate = datetime.getDate() < 10 ? `0${datetime.getDate()}` : datetime.getDate();
        result = `${Nyear}-${Nmonth}-${Ndate}`;
    }

    return result;
}
export function initIM(){
    return new Promise((resolve, reject) => {
        getAppId().then((res)=>{
            const SDKAppID=res;
            let options={
                SDKAppID
            }
            let tim=TIM.create(options);
            tim.setLogLevel(1);
            tim.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});
            Vue.prototype.tim=tim;
            Vue.prototype.TIM=TIM;
            tim.on(TIM.EVENT.SDK_READY, onSdkReady);
            tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
            tim.on(TIM.EVENT.MESSAGE_MODIFIED, onMessageModified);
            tim.on(TIM.EVENT.MESSAGE_REVOKED, onMessageRevoked);
            tim.on(TIM.EVENT.MESSAGE_READ_BY_PEER, onMessageReadByPeer);
            tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, onConversationListUpdated);
            tim.on(TIM.EVENT.PROFILE_UPDATED, onProfileUpdated);
            tim.on(TIM.EVENT.BLACKLIST_UPDATED, onBlacklistUpdated);
            tim.on(TIM.EVENT.FRIEND_LIST_UPDATED, onFriendListUpdated);
            tim.on(TIM.EVENT.FRIEND_GROUP_LIST_UPDATED, onFriendGroupListUpdated);
            tim.on(TIM.EVENT.KICKED_OUT, onKickedOut);
            tim.on(TIM.EVENT.NET_STATE_CHANGE, onNetStateChange);
            resolve('初始化成功');
        }).catch((res)=>{
            reject('IM初始化失败');
        })
    })
}
function onSdkReady(){
    const user=Cookies.get('user')?JSON.parse(Cookies.get('user')):null;
    if(user){
        Vue.prototype.tim.updateMyProfile({
            nick: user.realName, avatar: user.faceUrl
        })
    }
    Vue.prototype.$bus.$emit('onSdkReady');
}
function onMessageReceived(e){
    Vue.prototype.$bus.$emit('onMessageReceived',e);
}
function onMessageModified(e){
    Vue.prototype.$bus.$emit('onMessageModified',e);
}
function onMessageRevoked(e){
    Vue.prototype.$bus.$emit('onMessageRevoked',e);
}
function onMessageReadByPeer(e){
    Vue.prototype.$bus.$emit('onMessageReadByPeer',e);
}
function onConversationListUpdated(e){
    Vue.prototype.$bus.$emit('onConversationListUpdated',e);
}
function onProfileUpdated(e){
    Vue.prototype.$bus.$emit('onProfileUpdated',e);
}
function onBlacklistUpdated(e){
    Vue.prototype.$bus.$emit('onBlacklistUpdated',e);
}
function onFriendListUpdated(e){
    Vue.prototype.$bus.$emit('onFriendListUpdated',e);
}
function onFriendGroupListUpdated(e){
    Vue.prototype.$bus.$emit('onFriendGroupListUpdated',e);
}
function onKickedOut(e){
    if(e.data.type!==TIM.TYPES.KICKED_OUT_REST_API){
        Vue.prototype.$message({
            type:'error',
            message:'您的账号在其他设备登录，您被迫下线',
            duration:0,
            showClose:true
        })
    }
    Vue.prototype.$bus.$emit('onKickedOut',e);
}
function onNetStateChange(e){
    // v2.5.0 起支持
    // event.data.state 当前网络状态，枚举值及说明如下：
    // TIM.TYPES.NET_STATE_CONNECTED - 已接入网络
    // TIM.TYPES.NET_STATE_CONNECTING - 连接中。很可能遇到网络抖动，SDK 在重试。接入侧可根据此状态提示“当前网络不稳定”或“连接中”
    // TIM.TYPES.NET_STATE_DISCONNECTED - 未接入网络。接入侧可根据此状态提示“当前网络不可用”。SDK 仍会继续重试，若用户网络恢复，SDK 会自动同步消息
    switch (e.data.state){
        case TIM.TYPES.NET_STATE_CONNECTING:
            Vue.prototype.imTips=Vue.prototype.$message({
                message:'网络不稳定，重新连接中',
                type:"warning",
                duration:1000*60*2,
            })
            break;
        case TIM.TYPES.NET_STATE_DISCONNECTED:
            Vue.prototype.imTips=Vue.prototype.$message({
                message:'网络似乎开小差了，换个网络环境试试',
                type:"error",
                duration:1000*60*2,
            })
            break;
        case TIM.TYPES.NET_STATE_CONNECTED:
            if(Vue.prototype.imTips){
                Vue.prototype.imTips.close();
            }
            break;
    }
    Vue.prototype.$bus.$emit('onNetStateChange',e);
}
